package com.joven.core.controller;

import com.joven.core.constant.ResultInfo;
import com.joven.core.utils.lockUtil.JedisDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author joven_wong
 * 2021/6/30 15:42
 * 占用锁模式 不会自动切换
 */
@RestController
@RequestMapping("/jedis")
public class TestJedisLockController {
    @Autowired
    JedisDistributedLock jedisDistributedLock;

    @GetMapping("/test1")
    public ResultInfo jedisLock1(){
        String lockKey = "yu";
        boolean flag;
        String lockId = jedisDistributedLock.occupyDistributedLock(lockKey);
        try {
            //业务代码
            System.out.println(lockId);
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            flag = jedisDistributedLock.releaseDistributedLock(lockKey, lockId);
        }
        flag = jedisDistributedLock.releaseDistributedLock(lockKey, lockId);
        return ResultInfo.success(flag);
    }

    @GetMapping("/test2")
    public ResultInfo jedisLock2(){
        String lockKey = "yu";
        boolean flag;
        String lockId = jedisDistributedLock.occupyDistributedLock(lockKey);
        try {
            //业务代码
            System.out.println(lockId);
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            flag = jedisDistributedLock.releaseDistributedLock(lockKey, lockId);
        }
        flag = jedisDistributedLock.releaseDistributedLock(lockKey, lockId);
        return ResultInfo.success(flag);
    }
}
